package cn.iocoder.yudao.module.reading.controller.app.auth;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.reading.controller.app.auth.vo.ReadingLoginReqVO;
import cn.iocoder.yudao.module.reading.controller.app.auth.vo.ReadingLoginRespVO;
import cn.iocoder.yudao.module.reading.controller.app.auth.vo.ReadingRegisterReqVO;
import cn.iocoder.yudao.module.reading.controller.app.auth.vo.ReadingWxLoginReqVO;
import cn.iocoder.yudao.module.reading.service.auth.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 绘本阅读 APP - 认证
 *
 * @author 李晨
 */
@Tag(name = "绘本阅读 APP - 认证")
@RestController("readingAuthController") // 指定Bean名称避免冲突
@RequestMapping("/reading/auth")
@Validated
@Slf4j
public class AuthController {

    @Resource
    private AuthService authService;

    @Resource
    private SecurityProperties securityProperties;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    @PreAuthorize("permitAll()")
    public CommonResult<ReadingLoginRespVO> login(@RequestBody @Valid ReadingLoginReqVO reqVO) {
        return success(authService.login(reqVO));
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    @PreAuthorize("permitAll()")
    public CommonResult<ReadingLoginRespVO> register(@RequestBody @Valid ReadingRegisterReqVO reqVO) {
        return success(authService.register(reqVO));
    }

    @PostMapping("/wx-login")
    @Operation(summary = "微信登录")
    @PreAuthorize("permitAll()")
    public CommonResult<ReadingLoginRespVO> wxLogin(@RequestBody @Valid ReadingWxLoginReqVO reqVO) {
        return success(authService.wxLogin(reqVO));
    }

    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    @PreAuthorize("permitAll()")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (token != null) {
            authService.logout(token);
        }
        return success(true);
    }

}
